<template>
  <inject-template :item="item" :pageId="pageId" :popId="popId">
    <template v-slot:common>
      <div class="wb-timer">
        <!-- <van-button :style="item.styles">{{ timeStr }}</van-button> -->
        <van-count-down
          :style="item.styles"
          ref="countDown"
          :time="countTime"
          :auto-start="autoStart"
          :format="timerFormat"
          @finish="timerFinished"
        />
      </div>
    </template>
   </inject-template>
</template>

<script>
import InjectTemplate from '@/components/inject-template.vue'
import { utils } from '@/components/utils/utils'
import { CONTROL_TYPES, TIMER_TYPES_MAP, TIMER_PATTERN_MAP } from '@/common/const'
import { pageTemplate } from '@/components/utils/page-template'
import { wbBase } from '@/components/utils/wbBase'
import { EventBus } from '@/store/index'
import { reactive } from 'vue'

export default {
  name: 'WbTimer',
  mixins: [utils, pageTemplate, wbBase],
  setup () {
    const state = reactive({
      countTime: 0,
      timerFormat: '00小时00分钟00秒',
      autoStart: false,
    })
    state.timeTimerCb = null
    return state
  },
  components: {
    InjectTemplate,
  },
  created() {
    this.setTimeFormat();
    if(this.isH5Edit){
      return
    }
    EventBus.$off("timerStart", this.onTimerStart)
    EventBus.$on("timerStart", this.onTimerStart)
    EventBus.$off("timerPause", this.onTimerPause)
    EventBus.$on("timerPause", this.onTimerPause)
  },
  mounted: function () {
    if(!this.isH5Edit){
      this.refresh()
      _.merge(this.controls[this.item.id][CONTROL_TYPES.timer].data, this.$refs.countDown.timeData);
    }
  },
  methods: {
    setTimeFormat(){
      if(this.commonAttr.pattern == TIMER_PATTERN_MAP.hour.value){
        this.timerFormat = TIMER_PATTERN_MAP.hour.format
      }else if(this.commonAttr.pattern == TIMER_PATTERN_MAP.day.value){
        this.timerFormat = TIMER_PATTERN_MAP.day.format
      }else if(this.commonAttr.pattern == TIMER_PATTERN_MAP.hourTimeStr.value){
        this.timerFormat = TIMER_PATTERN_MAP.hourTimeStr.format
      } else if(this.commonAttr.pattern == TIMER_PATTERN_MAP.secondStr.value) {
        this.timerFormat = TIMER_PATTERN_MAP.secondStr.format
      }
    },
    onTimerPause(){
      this.$refs.countDown.pause()
    },
    onTimerStart(){
      let controlData = this.getItemControls[CONTROL_TYPES.timer].data
      this.countTime = parseInt(controlData.countdown)*1000
      this.$refs.countDown.reset()
      this.autoStart = true
      this.$refs.countDown.start()
    },
    timerFinished() {
      let controlData = this.getItemControls[CONTROL_TYPES.timer].data
      if(controlData.type === TIMER_TYPES_MAP.activityCountdownTime) {
        let event = { type: 'initTime', controlId:CONTROL_TYPES.timer }
        this.initPost('/feinit/timer', {event, site_id: this.siteInfo.id, com_id: this.item.id, action: 'get' })
      } else if(controlData.type === TIMER_TYPES_MAP.countdown) {
        EventBus.$emit("itemClick", {id: this.item.id, index: 0});
      }
      if(controlData.popId > 0){
        this.showPop(controlData.popId)
      }
      EventBus.$emit("timerEnd")
    },
    refresh(){
      let controlData = this.getItemControls[CONTROL_TYPES.timer].data
      if(controlData.type === TIMER_TYPES_MAP.activityCountdownTime){
        this.activityCountdownTime(controlData)
      }else if(controlData.type === TIMER_TYPES_MAP.countdown){
        //计数
        this.countTime = 0;
        // this.onTimerStart();
      }else{
        //正计时 倒计时
        // let start
        let end
        let now
        if(controlData.time && controlData.time.length > 0){
          if(controlData.type == TIMER_TYPES_MAP.activityStartEndTime){
            // start = new Date(controlData.time).getTime()
            end = new Date(controlData.endTime).getTime()
            now = new Date().getTime()
          }else{
            end = new Date(controlData.time).getTime()
            now = new Date().getTime()
          }
        }else{
          this.showToast('时间没有设置哦！！')
        }
        // if(startTime < 0) {
        //   isDisabled_ = true
        //   // this.showToast("亲，活动还未开始！！请耐心等待！！");
        // }else if(endTime < 0){
        //   isDisabled_ = true
        //   // this.showToast("亲， 活动已结束了哦！！");
        // }else{
        //   isDisabled_ = false
        // }
        let msec
        if(controlData.type === TIMER_TYPES_MAP.positiveTime){
          msec = now - end
        }else if(controlData.type === TIMER_TYPES_MAP.countdownTime){
          msec = end - now
        }else if(controlData.type == TIMER_TYPES_MAP.activityStartEndTime){
          msec = end - now
        }
        if(msec <= 0){
          EventBus.$emit("timeComplete")
        }else{
          this.countTime = msec
          this.autoStart = true
          this.$refs.countDown.start()
          this.$nextTick(() => {
            _.merge(this.controls[this.item.id][CONTROL_TYPES.timer].data, this.$refs.countDown.timeData);
          })
        }
      }
    },
    activityCountdownTime(controlData) {
      if(controlData.time && controlData.time.length > 0){
        let now = (new Date(this.timeObj.serverTime.replace(/-/g,  "/"))).valueOf();
        let end = (new Date(controlData.time.replace(/-/g,  "/"))).valueOf();
        let msec = end - now
        this.countTime = msec
        if(msec >= 0){
          this.$store.commit("updateIsTimerEnd", {isTimerEnd :  true})
          this.autoStart = true
          this.$refs.countDown.start()
        }else{
          //活动结束 直接弹出结果 ext_1不能为0 为零就直接停在pop3了
          if(controlData.popId){
            this.showPop(controlData.popId);
          }
        }
      }else{
        this.timeTimerCb = window.setInterval( () => {
          let controlData = this.getItemControls[CONTROL_TYPES.timer].data;
          if(controlData.time.length > 0){
            this.$store.commit("updateIsTimerStart", { isTimerStart: true })
            window.clearInterval(this.timeTimerCb)
            this.refresh()
          }else{
            let event = { type: 'initTime', controlId:CONTROL_TYPES.timer }
            this.initPost('/feinit/timer', {event, site_id: this.siteInfo.id, com_id: this.item.id, action: 'get' })
          }
        }, 1000)
      }
    },
    onRefreshCommonAttr() {
      this.setTimeFormat();
    },
  },
  beforeUnmount() {
    if(this.isH5Edit) {
      EventBus.$off('refreshCommonAttr', this.onRefreshCommonAttr);
      return
    }
    EventBus.$off("timerStart", this.onTimerStart)
    EventBus.$off("timerPause", this.onTimerPause)
  },
};
</script>

<style lang="scss">
.wb-timer{
  width: inherit;
  height: inherit;

  .van-count-down{
    width: inherit;
    height: inherit;
    text-align: center;
    display: flex;
    align-content: center;
    align-items: center;
    justify-content: center;
    justify-items: center;
  }
}
</style>
